/**
 * 广寒宫
 * 网址:www.guanghangong.xyz
 */
package com.moon.admin.tools.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.moon.admin.framework.domain.Kv;
import com.moon.admin.framework.domain.MoonPage;
import com.moon.admin.framework.mybatisplus.query.Condition;
import com.moon.admin.framework.springmvc.domain.R;
import com.moon.admin.framework.util.ToolUtils;
import com.moon.admin.monitor.domain.Datasource;
import com.moon.admin.tools.entity.DatasourceEntity;
import com.moon.admin.tools.servcie.DatasourceService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;

/**
 * 数据源配置表 控制器
 *
 * @author ninlong
 */
@RestController
@RequestMapping("/tools/datasource")
@Api(value = "数据源配置表", tags = "数据源配置表接口")
public class DatasourceController {

	@Autowired
	private DatasourceService datasourceService;

	/**
	 * 分页 数据源配置表
	 */
	@PostMapping("/list")
	@ApiOperation(value = "数据源配置分页", notes = "传入datasource")
	public R<MoonPage<DatasourceEntity>> list(@RequestBody Datasource datasource) {
		IPage<DatasourceEntity> pages = datasourceService.page(Condition.getPage(datasource),
				Condition.getQueryWrapper(new DatasourceEntity(),datasource));
		return R.success(MoonPage.of(pages));
	}

	/**
	 * 新增或修改 数据源配置表
	 */
	@PostMapping("/submit")
	@ApiOperation(value = "新增或修改数据源配置", notes = "传入datasource")
	public R<Boolean> submit(@RequestBody DatasourceEntity datasourceEntity) {
		datasourceEntity.setUrl(datasourceEntity.getUrl().replace("&amp;", "&"));
		return R.status(datasourceService.saveOrUpdate(datasourceEntity));
	}


	/**
	 * 删除 数据源配置表
	 */
	@GetMapping("/removeByIds")
	@ApiOperation(value = "逻辑删除", notes = "传入ids")
	public R<Boolean> removeByIds(@ApiParam(value = "主键集合", required = true)String ids) {
		return R.status(datasourceService.removeByIds(ToolUtils.toLongList(ids)));
	}

	/**
	 * 数据源列表
	 */
	@GetMapping("/select")
	@ApiOperation(value = "下拉数据源配置", notes = "查询列表")
	public R<List<Kv>> select() {
		List<Kv> list = datasourceService.list().stream().map(entity->Kv.builder()
				.label(entity.getName()).value(String.valueOf(entity.getId()))
				.build()).collect(Collectors.toList());
		return R.success(list);
	}
}